from typing import Dict, Any
from langgraph.graph import StateGraph
from pydantic import BaseModel, Field
from intelli_port.data_layer.clients import mysql_execute_read


class ServiceBaggage(BaseModel):
    type: str = Field(default="baggage")
    policy: str
    overweight_fee_cny: float | None = None


def build_baggage_subgraph():
    g = StateGraph(dict)

    def baggage_info(state: Dict[str, Any]) -> Dict[str, Any]:
        slots = state.get("slots") or {}
        text = state.get("text") or ""
        policy = "随身行李限额7kg，托运行李按航司规定办理"
        fee = None
        try:
            import re
            m = re.search(r"(\d+\.?\d*)\s*kg", text.lower())
            if m:
                w = float(m.group(1))
                # 超重计算：默认免额 23kg，超重部分乘以费率
                kv_free = mysql_execute_read("SELECT `value` FROM kv_config WHERE `key`=%s", ("baggage.free_weight_kg",), fetch="one").get("rows", [])
                kv_rate = mysql_execute_read("SELECT `value` FROM kv_config WHERE `key`=%s", ("baggage.overweight.fee_per_kg",), fetch="one").get("rows", [])
                free_w = float(kv_free[0][0]) if kv_free and kv_free[0] and kv_free[0][0] else 23.0
                rate = float(kv_rate[0][0]) if kv_rate and kv_rate[0] and kv_rate[0][0] else 80.0
                if w > free_w:
                    fee = round((w - free_w) * rate, 2)
        except Exception:
            fee = None
        try:
            r = mysql_execute_read("SELECT `value` FROM kv_config WHERE `key`=%s", ("baggage.policy.default",), fetch="one").get("rows", [])
            if r and r[0] and r[0][0]:
                policy = str(r[0][0])
        except Exception:
            pass
        svc = ServiceBaggage(policy=policy, overweight_fee_cny=fee).model_dump()
        return {**state, "service": svc}

    g.add_node("baggage_info", baggage_info)
    g.set_entry_point("baggage_info")
    return g.compile()